package cn.hanyx.vlog.articleservice.controller;

import cn.hanyx.vlog.articleservice.annotation.JwtToken;
import cn.hanyx.vlog.articleservice.dto.ResponseObject;
import cn.hanyx.vlog.articleservice.entity.User;
import cn.hanyx.vlog.articleservice.service.ArticleService;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * ArticleController
 *
 * @author hanyx
 * @date 2021/11/04
 */
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @JwtToken(requird = false)
    @GetMapping("/list")
    public ResponseObject list(@RequestAttribute(value = "$user", required = false) User user) {
        return new ResponseObject("0", "success", articleService.list(user));
    }

    @GetMapping("/rule_setting")
    //代码配置Sentinel限流规则
    public String initFlowRule() {
        //规则集合
        List<FlowRule> rules = new ArrayList<>();
        //创建新的规则对象,"/list"就是资源名
        FlowRule rule = new FlowRule("/article/list");
        //"直接"策略
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);
        //采用QPS限速模式
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //限制为QPS 为100
        rule.setCount(100);
        //流控效果设置为"预热"
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP);
        //预热时间20秒
        rule.setWarmUpPeriodSec(20);
        //来源设置为默认所有default
        rule.setLimitApp("default");
        rules.add(rule);
        //设置,FlowRuleManager是Sentinel规则管理器
        FlowRuleManager.loadRules(rules);
        return "SUCCESS";
    }

    @JwtToken(requird = false)
    @GetMapping("/dosth")
    public ResponseObject dosth() {
        return new ResponseObject("hello");
    }
}
